package utils

import (
	"io"
	"log"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"time"
)

type Request struct {
	URL     string
	Method  string
	Timeout time.Duration
	//InitCookie string
	Headers map[string]string

	ProxyUrl string
}

func (r *Request) Do() []byte {
	//创建cookiejar
	jar, err := cookiejar.New(nil)
	if err != nil {
		panic("Error creating cookie jar:" + err.Error())
	}

	var client *http.Client
	//开启
	if len(r.ProxyUrl) > 0 {
		proxyUrl, err := url.Parse(r.ProxyUrl)
		if err != nil {
			log.Fatalln("解析代理路径失败:", err)
		}
		transport := &http.Transport{
			Proxy: http.ProxyURL(proxyUrl),
		}
		//创建一个http客户端 并有代理
		client = &http.Client{
			Jar:       jar,
			Timeout:   r.Timeout,
			Transport: transport,
		}
	} else {
		//创建一个http客户端 无代理
		client = &http.Client{
			Jar:     jar,
			Timeout: r.Timeout,
		}
	}

	//设置初始cookie
	//initialCookie := &http.Cookie{
	//	Name:  r.InitCookie,
	//	Value: r.InitCookie,
	//}

	//创建URL对象
	//url, err := url2.Parse(r.URL)
	//if err != nil {
	//	panic("Error parsing URL:" + err.Error())
	//}

	//将初始的cookie添加到cookiejar中
	//jar.SetCookies(url, []*http.Cookie{initialCookie})

	//创建一个http请求
	req, err := http.NewRequest(r.Method, r.URL, nil)

	if err != nil {
		panic("Error creating request:" + err.Error())
	}

	for key, value := range r.Headers {
		req.Header.Set(key, value)
	}

	//发送客户端请求
	resp, err := client.Do(req)
	if err != nil {
		panic("Error making request:" + err.Error())
	}
	defer resp.Body.Close()

	res, err := io.ReadAll(resp.Body)
	if err != nil {
		panic("请求发生错误：" + err.Error())
	}

	return res
}
